package com.many2many;

import java.util.HashSet;
import java.util.Iterator;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
	public static void main(String[] args) {
		add_many2many_relationship();
//		delete_addr();
//		delete_relationship();
//		query_custs();
	}

	public static void add_many2many_relationship() {
		CustomerDAO c_dao = new CustomerDAO();
		AddressDAO a_dao = new AddressDAO();

		Customer cust1 = (Customer) c_dao.findById(1);
		Customer cust2 = (Customer) c_dao.findById(2);

		Address addr1 = (Address) a_dao.findById(1);
		Address addr2 = (Address) a_dao.findById(2);

		// Session session = c_dao.getSession();
		Session session = a_dao.getSession();
		try {
			Transaction tran = session.beginTransaction();

			// c_dao.update(loginUser);
			// a_dao.delete(address);

			cust1.setAddresses(new HashSet(0));
			cust2.setAddresses(new HashSet(0));

			cust1.getAddresses().add(addr1);
			cust1.getAddresses().add(addr2);

			cust2.getAddresses().add(addr1);
			cust2.getAddresses().add(addr2);

			session.update(cust1);
			session.update(cust2);
			tran.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}

	public static void delete_addr() {
		AddressDAO a_dao = new AddressDAO();
		Address addr1 = (Address) a_dao.findById(1);

		Session session = a_dao.getSession();
		
		Transaction tran = null;
		try {
			tran = session.beginTransaction();
			a_dao.delete(addr1);
			tran.commit();
		} catch (Exception e) {
			if (tran != null)
				tran.rollback();
		} finally {
			session.close();
		}
	}

	public static void delete_relationship() {
		CustomerDAO c_dao = new CustomerDAO();
		AddressDAO a_dao = new AddressDAO();

		Session session = a_dao.getSession();

		Customer cust = (Customer) c_dao.findById(1);
		Address address = (Address) a_dao.findById(1);
		cust.getAddresses().remove(address);
		Transaction tran = null;
		try {
			tran = session.beginTransaction();
			session.update(cust);
			tran.commit();
		} catch (Exception e) {
			if (tran != null)
				tran.rollback();
		} finally {
			session.close();
		}
	}

	public static void query_custs() {
		CustomerDAO c_dao = new CustomerDAO();
		AddressDAO a_dao = new AddressDAO();

		Address addr1 = (Address) a_dao.findById(1);
		a_dao.delete(addr1);
		a_dao.getSession().update(a_dao);
		Iterator it = addr1.getCustomers().iterator();

		// Session session = c_dao.getSession();
		while (it.hasNext()) {
			Customer c = (Customer) it.next();
			System.out.println(c.getAccount());
		}
		a_dao.getSession().close();
	}
}
